package com.yymx.toback.common.redis;


import com.yymx.toback.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName IdGenerator
 * @Description
 * @Author zyg
 * @Date 2019/3/23 14:49
 **/
@Component
public class IdGenerator {

    @Autowired
    private  RedisUtil redisUtil;

    /**
     * 生成订单编号
     * @param type
     * @return
     */
    public String generateContainsTimeSerialFromRedis(String type){
        //合同编号规则: BNF + 当前日期 + 六位编号，编号每天从1开始递增
        String currentDate = DateUtils.getDate("yyyyMMdd");
        String key = type + currentDate;
        long count = redisUtil.incr(key, 1);
        if (count == 1) {
            redisUtil.expireAt(key, getTimeout());
        }
        return String.format("%s%s%s",type, currentDate, String.format("%06d", count));
    }


    /**
     * 生成客户流水号
     * @param type
     * @return
     */
    public String customerSerialNo(String type){
        String currentDate = DateUtils.getDate("yyyyMMdd");
        String key = type + currentDate;
        long count = redisUtil.incr(key, 1);
        if (count == 1) {
            redisUtil.expireAt(key, getTimeout());
        }
        return String.format("%s%s%s",type, currentDate, String.format("%04d", count));
    }

    private Date getTimeout() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
}
